/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: InputView.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.view;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import io.bhex.app.R;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.baselib.utils.PixelUtils;

/**
 * ================================================
 * 描   述：自定义自动悬浮提示文案输入框
 * ================================================
 */

public class InputView extends LinearLayout implements View.OnClickListener{
    private EditText mInputEd;
    private CheckBox mInputShow;
    private ImageView mInputClear;
//    private TextInputLayout mInputLayout;
    private inputCheckListener listener;
    RelativeLayout.LayoutParams btnsLayoutParams;

    public final static int SILENTMODE = 0;
    public final static int NORMALMODE = 1;
    public final static int PWDMODE = 2;
    private int mMode = NORMALMODE;
    private int mNum = 6;
    //错误提示
    private TextView errorTxt;
    private LinearLayout mInputAction;
    private String hint="";
    private boolean editable;

    public InputView(Context context) {
        super(context);
        init(context, null);
    }

    public InputView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public InputView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.InputView);
        hint = typedArray.getString(R.styleable.InputView_hint);
        editable = typedArray.getBoolean(R.styleable.InputView_editable,true);
        mMode = typedArray.getInt(R.styleable.InputView_textType,-1);
        LayoutInflater.from(context).inflate(R.layout.view_input_edittext_layout,
                this, true);
        setOrientation(HORIZONTAL);
        initView();
        addEvent();
        setInputMode(mMode);
    }

    public void setListener(inputCheckListener listener) {
        this.listener = listener;
    }

    public void setInputMode(int mode) {
        mMode = mode;
        switch (mode) {
            case SILENTMODE:
                mInputShow.setVisibility(View.GONE);
                mInputClear.setVisibility(View.GONE);
                break;
            case NORMALMODE:
                mInputEd.setInputType(InputType.TYPE_CLASS_PHONE);
                mInputShow.setVisibility(View.GONE);
                break;
            case PWDMODE:
                mInputShow.setVisibility(View.VISIBLE);
                mInputEd.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                mInputEd.setTypeface(Typeface.SANS_SERIF);
                break;
            default:
                break;
        }
    }

    public void setInputType(int inputType){
        mInputEd.setInputType(inputType);
    }

    public void setInputHint(String hint) {
//        mInputLayout.setHint(hint);
        mInputEd.setHint(hint);
    }

    public void setInputMax(int num) {
        mInputEd.setMaxLines(num);
    }

    public void setInputString(String content) {
        mInputEd.setText(content);
        mInputEd.setSelection(content.length());
    }

    private void initView() {
        mInputEd = findViewById(R.id.input_edit);
        setInputHint(hint);
        setInputNoEditable(editable);
        errorTxt = findViewById(R.id.error_text);

        mInputShow = findViewById(R.id.input_show);

        mInputAction = findViewById(R.id.input_action);
        mInputClear = findViewById(R.id.input_clear);

//        mInputLayout = (TextInputLayout) findViewById(R.id.input_layout);
//        mInputLayout.setHintTextAppearance(R.style.EditTextHintStyle);
    }

    private void setInputNoEditable(boolean editable) {
        mInputEd.setEnabled(editable);
        mInputEd.setTextColor(SkinColorUtil.getDark(this.getContext()));
    }

    private void addEvent() {
        mInputClear.setOnClickListener(this);

        mInputShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    mInputEd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    mInputEd.setInputType(InputType.TYPE_CLASS_TEXT
                            | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }

                if (mMode==PWDMODE) {
                    checkPasswdFont(mInputEd.getText().toString());
                }
            }
        });

        mInputEd.addTextChangedListener(new inputChangeListener());
    }

    /**
     * 设置输入框内左边距
     * @param left
     */
    public void setPaddingLeft(int left){
        mInputEd.setPadding(left,mInputEd.getPaddingTop(),mInputEd.getPaddingRight(),mInputEd.getPaddingBottom());
    }

    /**
     * 设置输入框内右边距
     * @param right
     */
    public void setPaddingRight(int right){
        int inputActionWidth = PixelUtils.dp2px(30);
        mInputEd.setPadding(mInputEd.getPaddingLeft(),mInputEd.getPaddingTop(),right+inputActionWidth,mInputEd.getPaddingBottom());
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mInputAction.getLayoutParams();
        layoutParams.rightMargin = right+PixelUtils.dp2px(5);

        mInputAction.setLayoutParams(layoutParams);
    }

    /**
     * 提示错误
     * @param error
     */
    public void setError(String error) {
        if (TextUtils.isEmpty(error)||TextUtils.isEmpty(mInputEd.getText().toString())) {
            errorTxt.setText("");
            errorTxt.setVisibility(GONE);
        }else{
            errorTxt.setVisibility(VISIBLE);
            errorTxt.setText(error);
        }
    }

    public TextView getErrorTextView() {
        return errorTxt;
    }

    /**
     * 设置焦点改变监听
     * @param listener
     */
    public void setOnFocusChangeListener(OnFocusChangeListener listener){
        mInputEd.setOnFocusChangeListener(listener);
    }

    public void addTextWatch(TextWatcher mTextWatcher) {
        mInputEd.addTextChangedListener(mTextWatcher);
    }

    public EditText getEditText() {
        return mInputEd;
    }

    public void setInputEditFocusable(boolean isFocus) {
        if (mInputEd != null) {
            mInputEd.setFocusable(isFocus);
//            mInputEd.setSelection(mInputEd.getText().toString().length());
            mInputEd.setPressed(true);
        }
    }

    private class inputChangeListener implements TextWatcher {

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @SuppressLint("NewApi")
        @Override
        public void afterTextChanged(Editable edit) {
            if (listener != null && edit.toString().length() != mNum) {
                listener.checkStatus();
            }
            if (mMode == SILENTMODE){
                return;
            }else{
                if (TextUtils.isEmpty(edit.toString())||!editable) {
                    mInputClear.setVisibility(View.GONE);
                } else {
                    mInputClear.setVisibility(View.VISIBLE);
                }
            }

        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence arg0, int arg1, int arg2,
                                  int arg3) {
            if (TextUtils.isEmpty(arg0)) {
                errorTxt.setVisibility(GONE);
            }else{
            }

            if (mMode==PWDMODE) {
                checkPasswdFont(arg0);
            }
        }
    }

    /**
     * 改变密码字体
     * @param arg0
     */
    private void checkPasswdFont(CharSequence arg0) {
        Typeface typeface = mInputEd.getTypeface();
        if (TextUtils.isEmpty(arg0)) {
            if (typeface==null||!typeface.equals(Typeface.SANS_SERIF)) {
                mInputEd.setTypeface(Typeface.SANS_SERIF);
            }
        }else{
            if (mInputShow.isChecked()) {
                if (typeface==null||!typeface.equals(Typeface.SANS_SERIF)) {
                    mInputEd.setTypeface(Typeface.SANS_SERIF);
                }
            }else{
                if (typeface==null||!typeface.equals(Typeface.MONOSPACE)) {
                    mInputEd.setTypeface(Typeface.MONOSPACE);
                }
            }
        }

    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.input_clear) {
            mInputEd.setText("");
            mInputClear.setVisibility(View.GONE);
        }
    }

    public String getInputString() {
//        return mInputLayout.getEditText().getText().toString().trim();
        return mInputEd.getText().toString().trim();
    }

    public String getInputStringNoTrim() {
//        return mInputLayout.getEditText().getText().toString().trim();
        return mInputEd.getText().toString();
    }

    public interface inputCheckListener {
        void checkStatus();
    }
}
